package hey.dylan.service.impl;

import hey.dylan.form.UserForm;
import hey.dylan.model.LoginUser;
import hey.dylan.model.ResponseResult;
import hey.dylan.model.User;
import hey.dylan.service.LoginService;
import hey.dylan.utils.JwtUtil;
import hey.dylan.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(UserForm userForm) {

        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(userForm.getUsername(), userForm.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        // 如果认证没通过，给出提示
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("用户名或密码错误");
        }

        // 如果认证通过，使用userId生成一个jwt,将其存入ResponseResult后并返回
        LoginUser loginUser = (LoginUser)authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        User userInfo = editUserInfo(loginUser.getUser());
        String jwt = JwtUtil.createJWT(userId);
        Map<String,Object> map = new HashMap<>();
        map.put("token",jwt);
        map.put("user",userInfo);
        // 以userId作为key将完整的用户信息存入redis
        redisCache.setCacheObject("login:"+userId,loginUser);

        return new ResponseResult(200,"登陆成功",map);

    }

    private User editUserInfo(final User user) {
        User rtnUser = new User();
        rtnUser.setNickName(user.getNickName());
        rtnUser.setEmail(user.getEmail());
        rtnUser.setPhonenumber(user.getPhonenumber());
        rtnUser.setSex(user.getSex());
        rtnUser.setAvatar(user.getAvatar());
        return rtnUser;
    }

    @Override
    public ResponseResult logout() {

        // 获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken)SecurityContextHolder
                .getContext().getAuthentication();

        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userId = loginUser.getUser().getId();
        // 删除redis中的值
        redisCache.deleteObject("login:"+userId);
        return new ResponseResult(200,"注销成功");

    }

}
